package top.pengdong.pictureShare.tweet.controller;

import java.io.File;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.io.file.FileWriter;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import top.pengdong.pictureShare.common.model.*;
import top.pengdong.pictureShare.common.utils.Address;
import top.pengdong.pictureShare.common.utils.OauthUtils;
import top.pengdong.pictureShare.tweet.aspect.TweetAspect;
import top.pengdong.pictureShare.tweet.config.SensitiveWordConfig;
import top.pengdong.pictureShare.tweet.entity.*;
import top.pengdong.pictureShare.tweet.service.*;
import top.pengdong.pictureShare.tweet.service.impl.TimeSchedulingService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;


/**
 * 文章表
 *
 * @author chenshun
 * @email pengshi12138@outlook.com
 * @date 2022-04-25 16:55:46
 */
@RestController
@RequestMapping("api/tweet")
public class PsTweetController {

    @Autowired
    private PsTweetService psTweetService;

    @Autowired
    private PsTweetViewService psTweetViewService;

    @Autowired
    private PsTweetLikeForwardService psTweetLikeForwardService;


    @Resource
    private SensitiveWordConfig sensitiveWordConfig;

    @Resource
    private PsCountService psCountService;


    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = psTweetService.queryPage(params);

        return R.ok().put("result", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
        PsTweetEntity psTweetEntity = psTweetService.getById(id);

        return R.ok().put("result", psTweetEntity);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody PsTweetEntity psTweet){
        psTweetService.save(psTweet);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody PsTweetEntity psTweet){
        psTweetService.updateById(psTweet);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids){
        psTweetService.removeByIds(Arrays.asList(ids));

        return R.ok("删除成功");
    }


    /**
     *  开始实现自己的函数
     */

    /**
     * 文章详细信息 采用 cache 缓存进行设计
     */

    @RequestMapping("/tweet_info/{aid}")
    public R tweet_info(@PathVariable("aid") Long aid){
        LoginVal loginVal = OauthUtils.getCurrentUser();
        // 进行用户数据 浏览记录
        PsTweetViewEntity psTweetViewEntity = new PsTweetViewEntity();
        if (loginVal != null) psTweetViewEntity.setUserId(Long.valueOf(loginVal.getUserId()));
        psTweetViewEntity.setTweetId(aid);

        psTweetViewService.save(psTweetViewEntity);
		return psTweetService.getTweetInfo(aid);
    }

    /**
     * 图文章添加
     */
    @RequestMapping("/add")
    public R add(@RequestBody @Valid PsTweetEntity psTweet, HttpServletRequest request){
        LoginVal loginVal = OauthUtils.getCurrentUser();
        if (loginVal == null) return R.error(401, "未登录");

        return psTweetService.addTweet(psTweet, request, loginVal.getUserId());
    }

    /**
     * 修改文章
     */
    @RequestMapping(value = "/tweet_update", method = RequestMethod.POST)
    public R tweet_update(@RequestBody PsTweetEntity psTweet){
        return psTweetService.updateTweet(psTweet);
    }

    /**
     * 删除文章
     */
    @RequestMapping(value = "/tweet_delete", method = RequestMethod.GET)
    public R delete(@RequestParam("aid") Long tweetId){
        return psTweetService.deleteTweet(tweetId);
    }


    /**
     * 开始不是增上改查了，是功能页面了
     */


    /**
     * 用户转发操作，返回
     */
    @Cacheable(value={"TWEET_SHARE"},key="'tweet_' + #tweetId") // 指定key值为方法名字
    @RequestMapping(value = "/share_tweet", method = RequestMethod.GET)
    public R shareTweet(@RequestParam("aid") Long tweetId) {

       return psTweetService.shareWithCode(tweetId);
    }

    /**
     * 热榜计算问题
     * @return
     */

    @GetMapping("/type")
    public R show(@RequestParam(required = false) Integer page,
                     @RequestParam(required = false) Integer limit,
                    @RequestParam(required = false) String type,
                    @RequestParam(required = false) Integer label){
        if (page == null) page = 1;
        if (limit == null) limit = 10;
        if ("show".equals(type)) {
            return psTweetService.getViewShow(page, limit);
        }
        String paramType = null;
        String returnData = null;
        if ("hot".equals(type)) {
            paramType = SysConstant.HOT_SWEET;
            returnData = "热点";
        } else if ("collection".equals(type)){
            paramType = SysConstant.COLLECTION_SWEET;
            returnData = "最多收藏";
        } else if ("like".equals(type)) {
            paramType = SysConstant.LIKE_SWEET;
            returnData = "最多点赞";
        } else if ("share".equals(type)) {
            paramType = SysConstant.FORWARD_SWEET;
            returnData = "最多分享";
        } else if (label != null) {
            return psTweetService.getCategoryList(label, page, limit);
        } else {
            return R.error("参数错误");
        }
        Object o = psTweetService.getTypeTweets(
                paramType,
                page,
                limit
        );

        return R.ok(returnData + "数据返回").put("result", o);
    }

    /**
     * 用户操作方法
     */


    /**
     * 用户查看点赞 收藏状态
     * @return
     */
    @RequestMapping(value = "/user_action_status", method = RequestMethod.GET)
    public R user_like_status(@RequestParam("aid") Long[] aid) {
        return psTweetService.getUserStatus(aid);
    }



    /**
     * 用户点赞收藏操作
     * @param aid
     * @return
     */
    @RequestMapping(value = "/user_action", method = RequestMethod.GET)
    public R user_action(@RequestParam("ac") String action,
                         @RequestParam("type") String type,
                         @RequestParam("aid") Long aid) {
        LoginVal loginVal = OauthUtils.getCurrentUser();
        if (loginVal == null) {
            return R.error(ResultCode.CLIENT_AUTHENTICATION_FAILED.getCode(),
                    ResultCode.CLIENT_AUTHENTICATION_FAILED.getMsg());
        }
        Integer typeNum = null;
        if ("collection".equals(type)) {
            typeNum = 2;
        } else if ("like".equals(type)) {
            typeNum = 0;
        } else {
            return R.error("参数错误");
        }
        // 判断文章是不是存在
        PsTweetEntity byId = psTweetService.getById(aid);
        if (byId == null) {
            return R.error(400, "参数错误");
        } else if (byId.getIsLike() == 0) {
            return R.error(401, "文章不允许被点赞");
        }

        // 查看文章是不是被点赞了
        PsTweetLikeForwardEntity psTweetLikeForwardEntity = null;
        psTweetLikeForwardEntity = psTweetLikeForwardService.getBaseMapper().selectOne(
                new QueryWrapper<PsTweetLikeForwardEntity>()
                        .eq("user_id", Long.valueOf(loginVal.getUserId()))
                        .eq("tweet_id", aid)
                        .eq("type", typeNum)
        );
        // 点赞操作
        if ("add".equals(action)) {
            if (psTweetLikeForwardEntity != null) {
                return R.error(400, "用户已经操作过了");
            }
            psTweetLikeForwardEntity = new PsTweetLikeForwardEntity();
            psTweetLikeForwardEntity.setTweetId(aid);
            psTweetLikeForwardEntity.setUserId(Long.valueOf(loginVal.getUserId()));
            psTweetLikeForwardEntity.setType(typeNum);
            psTweetLikeForwardEntity.setStatus(1);
            psTweetLikeForwardService.save(psTweetLikeForwardEntity);
            return R.ok("操作成功");
        } else if ("delete".equals(action)) {
            if (psTweetLikeForwardEntity == null) {
                return R.error(ResultCode.UNCOLLECTION_STATUS.getCode(),
                        ResultCode.UNCOLLECTION_STATUS.getMsg());
            }
            // 设置函数设置为无效
            psTweetLikeForwardService.removeById(psTweetLikeForwardEntity);
            return R.ok("取消成功");
        } else {
            R.error("参数错误");
        }
        return R.error("错误操作");
    }

    /**
     * 通过redis 获取文章点赞评论数量 —— TODO 待设计
     * @param aid
     * @return
     */
    @RequestMapping(value = "/view_collection_share_num", method = RequestMethod.GET)
    public R view_collection_share_num(@RequestParam("aid") Long aid) {
        return psTweetService.getTweetCount(aid);
    }


    /**
     * 搜索功能
     */
    @GetMapping("/search")
    public R searchTweet(@RequestParam("word") String key,
                         @RequestParam("page") Integer page,
                         @RequestParam("limit") Integer limit) {
        page = page == null ? 0 : page;
        limit = limit == null ? 10 : limit;
        return psTweetService.searchTweet(key, page, limit);
    }

    /**
     * 远程调用接口
     */


    /**
     *
     * @param uid
     * @param type
     * @param page
     * @param limit
     * @return
     */
    @GetMapping(value = "/user_share_view_collection_type")
    public PageUtils findUserInfoTweet(@RequestParam("uid") Long uid, @RequestParam("type") Integer type,
                                  @RequestParam("page") Integer page, @RequestParam("limit") Integer limit) {
        return psTweetLikeForwardService.getUserInfoTweets(uid, type, page, limit);
    }

    @GetMapping("/user_tweets")
    public PageUtils getUserTweets(@RequestParam("uid") Long uid,
                         @RequestParam("page") Integer page, @RequestParam("limit") Integer limit) {
        return psTweetService.getUserTweets(uid, page, limit);
    }

    /**
     * 数据统计接口
     */


    /**
     * 获取所有的统计数据
     * @return
     */
    @GetMapping("/getCountList")
    public R getCountList() {
        List list = psTweetService.getCountList();
        Map<String, Object> map = new HashMap<>();
        map.put("counts", list);
        map.put("users", psCountService.getUserCount());
        map.put("map", psCountService.getUserMap());
        return R.ok("获取统计数据").put("result", map);
    }

    /**
     * 敏感词记录操作
     */

    /**
     * 敏感词处理函数
     */
    @GetMapping("/getSensitiveTxt")
    public R getText() {
        return R.ok("文本文件").put("result", SensitiveWordConfig.text);
    }



    /**
     * 写入文本中
     */
    @PostMapping("/setSensitiveTxt")
    public R setTxt(@RequestBody String text) {
        FileWriter writer = new FileWriter("txtTemplate/synthesize.txt");
        writer.write(text);
        sensitiveWordConfig.afterPropertiesSet();
        return R.ok("写入完成");
    }
}
